/**
 * 
 */
package gopi.labs.utils;

import gopi.labs.Connector.NameValue;
import gopi.labs.exceptions.InValidIdentifier;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONValue;
import org.json.simple.parser.ContainerFactory;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

/**
 * @author GS4
 * 
 */
public class DataHandler implements HttpHandler {

	/**
	 * @param args
	 */
	final String responseStr = "ok";

	public static void main(String[] args) {

	}

	private DataLoader loader;

	public DataHandler(DataLoader loader) {
		this.loader = loader;
	}

	@Override
	public void handle(HttpExchange exchange) throws IOException {

		InputStream request = exchange.getRequestBody();

		StringBuffer input = new StringBuffer();
		int ch;
		while ((ch = request.read()) != -1) {
			input.append((char) ch);
		}

		System.out.println("input.<" + input.toString() + ">");

		JSONParser parser = new JSONParser();
		ContainerFactory containerFactory = new ContainerFactory() {
			public List<Object> creatArrayContainer() {
				return new LinkedList<Object>();
			}

			public Map<Object, Object> createObjectContainer() {
				return new LinkedHashMap<Object, Object>();
			}
		};
		List<NameValue> data = new ArrayList<NameValue>();

		try {
			Map<?, ?> json = (Map<?, ?>) parser.parse(input.toString(),
					containerFactory);
			Iterator<?> iter = json.entrySet().iterator();
			System.out.println("==iterate result==");
			while (iter.hasNext()) {
				Map.Entry<?, ?> entry = (Map.Entry<?, ?>) iter.next();
				data.add(new NameValue(entry.getKey(), entry.getValue()));

				System.out.println(entry.getKey() + "=>" + entry.getValue());
			}
			loader.process(data);
			System.out.println("==toJSONString()==");
			System.out.println(JSONValue.toJSONString(json));

		} catch (ParseException pe) {
			System.out.println(pe);
		} catch (SQLException e) {

			e.printStackTrace();
		} catch (InValidIdentifier e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		exchange.sendResponseHeaders(200, responseStr.length());
		OutputStream os = exchange.getResponseBody();
		os.write(responseStr.getBytes());
		os.close();

	}

}
